package com.group.nepm.publicSuperviseDataManagement.controller;

import com.group.common.users.NEPGUser;
import com.group.common.utils.MyUtils;
import com.group.nepm.publicSuperviseDataManagement.entity.AssignData;
import com.group.neps.entity.City;
import com.group.neps.entity.Province;
import com.group.neps.entity.RowAqiData;
import com.group.neps.entity.RowAqiLevel;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.util.StringConverter;

import java.util.ArrayList;
import java.util.HashMap;

public class ThePublic_AssignController {

    //设置静态变量以获取数据
    private static RowAqiData selectedRowAqiData;
    private static int selectId;

    public static void NEPMsetSelectedRowAqiData(RowAqiData data,int id) {
        selectedRowAqiData = data;
        selectId = id;
    }

    public static RowAqiData NEPMgetSelectedRowAqiData() {
        return selectedRowAqiData;
    }

    @FXML
    private Label NEPSId;
    @FXML
    private Label NEPSMessage;
    @FXML
    private Label NEPSPhoneNumber;
    @FXML
    private Label NEPSLocation;
    @FXML
    private Label NEPSDescribe;
    @FXML
    private Label NEPSLevel;
    @FXML
    private Label NEPSTime;
    @FXML
    private CheckBox Whether;
    @FXML
    private ComboBox<Province> cobProvince;
    @FXML
    private ComboBox<City> cobCity;

    private HashMap<String, Province> provinceMap = new HashMap<>();

    @FXML
    private ComboBox<String> cobAssignToOther;
    @FXML
    private Button btnAssignToOther;
    @FXML
    private ComboBox<String> cobAssignToThis;
    @FXML
    private Button btnAssignToThis;
    @FXML
    private Label assignTo;
    @FXML
    private Label assignToOther;
    @FXML
    private Label provinceArea;
    @FXML
    private Label cityArea;


    public void adminOut(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/common/view/NEPMLoginView.fxml");
    }
    public void toPublicSuperviseDataList(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/publicSuperviseDataManagement/view/PublicSuperviseDataList.fxml");
    }
    public void toConfirmAqiDataList(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/publicSuperviseDataManagement/view/ConfirmAqiDataList.fxml");
    }
    public void toProvinceStatistic(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/statisticDataManagement/view/provinceStatistic.fxml");
    }
    public void toAqiDistributionStatistic(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/statisticDataManagement/view/aqiDistributionStatistic.fxml");
    }
    public void toAqiTendencyStatistic(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/statisticDataManagement/view/aqiTendencyStatistic.fxml");
    }
    public void toOtherDataStatistic(ActionEvent event) {
        MyUtils.navigateToView(event, "group/nepm/statisticDataManagement/view/otherDataStatistic.fxml");
    }
    public void initialize() {
        int id = selectId;
        String message = selectedRowAqiData.getUser().getUsername() +" " + selectedRowAqiData.getUser().getSex();
        String phoneNumber = selectedRowAqiData.getUser().getPhoneNumber();
        String location = selectedRowAqiData.getLocation().getProvince().getName() +" " + selectedRowAqiData.getLocation().getCity().getName() + " " + selectedRowAqiData.getLocation().getAddress();
        RowAqiLevel level = selectedRowAqiData.getAqiLevel();
        int key = level.ordinal()+1;
        String AQILevel = "";
        String describe = "";
        switch (key){
            case 1:{
                AQILevel = "一级 优";
                describe = "空气质量令人满意，基本无空气污染";
                break;
            }
            case 2:{
                AQILevel = "二级 良";
                describe = "空气质量可接受，但某些污染物可能对极少数异常敏感人群健康有较弱影响";
                break;
            }
            case 3:{
                AQILevel = "三级 轻度污染";
                describe = "易感人群症状有轻度加剧，健康人群出现刺激症状";
                break;
            }
            case 4:{
                AQILevel = "四级 中度污染";
                describe = "进一步加剧易感人群症状，可能对健康人群心脏、呼吸系统有影响";
                break;
            }
            case 5:{
                AQILevel = "五级 重度污染";
                describe = "心脏病和肺病患者症状显著加剧，运动耐受力降低，健康人群普遍出现症状";
                break;
            }
            case 6:{
                AQILevel = "六级 严重污染";
                describe = "健康人群运动耐受力降低，有明显强烈症状，提前出现某些疾病";
                break;
            }

        }
        NEPSLevel.setText(AQILevel);
        NEPSId.setText(String.format("%d", id));
        NEPSMessage.setText(message);
        NEPSPhoneNumber.setText(phoneNumber);
        NEPSLocation.setText(location);
        NEPSDescribe.setText(describe);
        NEPSLevel.setText(AQILevel);
        String time = selectedRowAqiData.getTime().toString();
        NEPSTime.setText(time);

        //设置显示
        updateVisibility(Whether.isSelected());

        Whether.selectedProperty().addListener((observable, oldValue, newValue) -> {
            updateVisibility(newValue);
        });

        //设置省区域、市区域
        // 设置ComboBox显示方式
        setupComboBoxDisplay();
        // 设置省份选择监听器
        setupProvinceSelectionListener();
        //设置网格员
        setupNEPGUser();
    }

    //显示设置
    private void updateVisibility(boolean selected) {
        cobProvince.setVisible(selected);
        provinceArea.setVisible(selected);
        cobCity.setVisible(selected);
        cityArea.setVisible(selected);
        assignToOther.setVisible(selected);
        cobAssignToOther.setVisible(selected);
        btnAssignToOther.setVisible(selected);
        cobAssignToThis.setVisible(!selected);
        assignTo.setVisible(!selected);
        btnAssignToThis.setVisible(!selected);
    }

    private void setupComboBoxDisplay() {
        // 设置省份ComboBox显示
        cobProvince.setConverter(new StringConverter<Province>() {
            @Override
            public String toString(Province province) {
                return province == null ? "" : province.getName();
            }

            @Override
            public Province fromString(String string) {
                return null; // 不需要实现
            }
        });

        // 设置城市ComboBox显示
        cobCity.setConverter(new StringConverter<City>() {
            @Override
            public String toString(City city) {
                return city == null ? "" : city.getName();
            }

            @Override
            public City fromString(String string) {
                return null; // 不需要实现
            }
        });

        // 填充省份数据
        provinceMap = MyUtils.readFileToHashMap("group/data/location_hashmap.dat");
        ObservableList<Province> provinces = FXCollections.observableArrayList(provinceMap.values());
        cobProvince.setItems(provinces);
    }

    private void setupProvinceSelectionListener() {
        cobProvince.getSelectionModel().selectedItemProperty().addListener((obs, oldProvince, newProvince) -> {
            cobCity.getItems().clear();

            if (newProvince != null) {
                // 获取选中省份的城市列表
                ObservableList<City> cities = FXCollections.observableArrayList(
                        newProvince.getCities().values()
                );
                cobCity.setItems(cities);
            }
        });
    }


    //创建指派结果类
    private void setupNEPGUser(){
        ArrayList<NEPGUser> nepgUsers = MyUtils.readFileToArrayList("group/data/nepg_userdata_arraylist.dat");
        ObservableList<String> nepgUserNames = FXCollections.observableArrayList();
        for (NEPGUser nepgUser : nepgUsers) {
            nepgUserNames.add(nepgUser.getUsername());
        }
        cobAssignToOther.setItems(nepgUserNames);
        cobAssignToThis.setItems(nepgUserNames);
    }

    //异地指派
    public void AssignToOther(ActionEvent actionEvent) {
        String id = NEPSId.getText();
        String message = NEPSMessage.getText();
        String phoneNumber = NEPSPhoneNumber.getText();
        String location = selectedRowAqiData.getLocation().getProvince().getName() +" " + selectedRowAqiData.getLocation().getCity().getName();
        String describe = NEPSDescribe.getText();
        String level = NEPSLevel.getText();
        String address = selectedRowAqiData.getLocation().getAddress();
        String nepguser = cobAssignToOther.getValue();

        if(cobProvince.getValue() == null || cobCity.getValue() == null || cobAssignToOther.getValue() == null){
            MyUtils.showAlert("分配失败","请选择省、市或网格员", "分配失败", Alert.AlertType.ERROR);
            return;
        }

        AssignData assignData = new AssignData(message + phoneNumber, location, address, level, describe, nepguser,id,selectedRowAqiData.getUser().getUsername());
        HashMap<String, AssignData> assignDataMap = MyUtils.readFileToHashMap("group/data/publicSupervise_assign_data_hashmap.dat");
        if(assignDataMap == null){
            assignDataMap = new HashMap<>();
        }


        assignDataMap.put(id, assignData);
        MyUtils.writeHashMapToFile("group/data/publicSupervise_assign_data_hashmap.dat", assignDataMap);
        MyUtils.showAlert("分配成功","异地指派成功", "分配成功", Alert.AlertType.INFORMATION);
        MyUtils.navigateToView(actionEvent, "group/nepm/publicSuperviseDataManagement/view/PublicSuperviseDataList.fxml");

    }

    //本地指派
    public void AssignToThis(ActionEvent actionEvent) {
        String id = NEPSId.getText();
        String message = NEPSMessage.getText();
        String phoneNumber = NEPSPhoneNumber.getText();
        String location = selectedRowAqiData.getLocation().getProvince().getName() +" " + selectedRowAqiData.getLocation().getCity().getName();
        String describe = NEPSDescribe.getText();
        String level = NEPSLevel.getText();
        String address = selectedRowAqiData.getLocation().getAddress();
        String nepguser = cobAssignToThis.getValue();

        if(cobAssignToThis.getValue() == null){
            MyUtils.showAlert("分配失败","请选择网格员", "分配失败", Alert.AlertType.ERROR);
            return;
        }
        AssignData assignData = new AssignData(message + phoneNumber, location, address, level, describe, nepguser, id,selectedRowAqiData.getUser().getUsername());
        HashMap<String, AssignData> assignDataMap = MyUtils.readFileToHashMap("group/data/publicSupervise_assign_data_hashmap.dat");
        if(assignDataMap == null){
            assignDataMap = new HashMap<>();
        }

        assignDataMap.put(id, assignData);
        MyUtils.writeHashMapToFile("group/data/publicSupervise_assign_data_hashmap.dat", assignDataMap);
        MyUtils.showAlert("分配成功","本地指派成功", "分配成功", Alert.AlertType.INFORMATION);
        MyUtils.navigateToView(actionEvent, "group/nepm/publicSuperviseDataManagement/view/PublicSuperviseDataList.fxml");

    }

    //返回
    public void back(ActionEvent actionEvent) {
        MyUtils.navigateToView(actionEvent, "group/nepm/publicSuperviseDataManagement/view/PublicSuperviseDataList.fxml");
    }
}
